import { Outlet, useLocation, useNavigate } from "react-router-dom";
import withAuth from "../../components/withAuth";
import { Image, Menu, Tooltip } from "antd";
import "./myLayout.css";
import {
  AccountBookOutlined,
  AppstoreOutlined,
  FolderOpenOutlined,
  GiftOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ShopOutlined,
  ShoppingCartOutlined,
  ShoppingOutlined,
  SnippetsOutlined,
} from "@ant-design/icons";
import Crumbs from "../../components/Crumbs/Crumbs";
import recursion from "../../utils/recursion";
import { useEffect, useState } from "react";

const items = [
  { icon: <AppstoreOutlined />, key: "/", label: "首页" },
  {
    icon: <ShoppingOutlined />,
    key: "/GoodManageTemplate",
    label: "商品管理",
    children: [
      {
        key: "/good",
        label: "主页",
      },
    ],
  },
  {
    icon: <ShopOutlined />,
    key: "/SupsupplierManageTemplate",
    label: "供应商管理",
    children: [
      {
        key: "/supplier",
        label: "主页",
      },
    ],
  },
  {
    icon: <ShoppingCartOutlined />,
    key: "/BusinessManageTemplate",
    label: "商家管理",
    children: [
      {
        key: "/business",
        label: "主页",
      },
    ],
  },
  {
    icon: <AccountBookOutlined />,
    key: "/OrderManageTemplate",
    label: "订单管理",
    children: [
      {
        key: "/order",
        label: "主页",
      },
    ],
  },
  {
    icon: <GiftOutlined />,
    key: "/PromoteManageTemplate",
    label: "活动管理",
    children: [
      {
        key: "/promote",
        label: "主页",
      },
    ],
  },
  {
    icon: <FolderOpenOutlined />,
    key: "/DictionaryTypeManageTemplate",
    label: "字典管理",
    children: [
      {
        key: "/dictionaryType",
        label: "主页",
      },
    ],
  },
  {
    icon: <SnippetsOutlined />,
    key: "/LogManageTemplate",
    label: "日志管理",
    children: [
      {
        key: "/log",
        label: "主页",
      },
    ],
  },
];

recursion(items, "children", (tree) => {
  tree.label = (
    <Tooltip title={tree.label} color={"cyan"} key={tree.key}>
      <span>{tree.label}</span>
    </Tooltip>
  );
});

function MyLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [openKeys, setOpenKeys] = useState([]);
  const [isCollection, setIsCollection] = useState(false);

  // 查找所有父级的编号集合（确保"/"是items里的第一个,否则将其移除并单独判断）
  const findParentList = (items, childrenName, key, parentList = []) => {
    for (let i = items.length - 1; i >= 0; i--) {
      const item = items[i];
      if (item[childrenName]) {
        const foundKey = findParentList(item[childrenName], childrenName, key, [
          ...parentList,
          item.key,
        ]);
        if (foundKey) return foundKey;
      }
      if (key.toLowerCase().startsWith(item.key.toLowerCase())) {
        return [...parentList, item.key];
      }
    }
  };

  useEffect(() => {
    // console.log(findParentList(items, "children", location.pathname));
    const openKeys = findParentList(items, "children", location.pathname);
    setOpenKeys(openKeys);
    setSelectedKeys([openKeys[openKeys.length - 1]]);
  }, [location.pathname]);

  const onClick = (e) => {
    navigate(e.key);
  };

  return (
    <>
      <div className="my-layout-container">
        <div
          className={
            isCollection ? "my-layout-menu-collection" : "my-layout-menu"
          }
        >
          <div className="my-layout-menu-logo-box">
            <div className="my-layout-menu-logo"></div>
            <div className="my-layout-menu-title">极简美食街</div>
          </div>
          <Menu
            onClick={onClick}
            className={"custom-menu"}
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            onSelect={(d) => setSelectedKeys(d.selectedKeys)}
            onOpenChange={(d) => setOpenKeys(d)}
            mode="inline"
            items={items}
          />
        </div>
        <div
          className={
            isCollection ? "my-layout-right-collection" : "my-layout-right"
          }
        >
          <div
            className={
              isCollection ? "my-layout-header-collection" : "my-layout-header"
            }
          >
            <div className="my-layout-header-box">
              <div className="menu-controll-btn">
                <span className="menu-controll-btn-icon">
                  {isCollection ? (
                    <MenuUnfoldOutlined
                      onClick={() => setIsCollection(false)}
                    />
                  ) : (
                    <MenuFoldOutlined onClick={() => setIsCollection(true)} />
                  )}
                </span>
              </div>
              <div className="my-layout-header-right">
                <div className="user-info">
                  <div className="user-avatar">
                    <Image
                      height={45}
                      preview={false}
                      src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
                    />
                  </div>
                  <div className="user-name">张三</div>
                </div>
              </div>
            </div>
          </div>
          <div className="my-layout-body">
            <Crumbs></Crumbs>
            <Outlet />
          </div>
        </div>
      </div>
    </>
  );
}

export default withAuth(MyLayout);
